function errorToast(title) {
  uni.showToast({
    icon: 'none',
    title: title,
  });
}

let baseUrl = '';

function statusCodeProcessing(statusCode) {
  switch (statusCode) {
    case 404:
      errorToast('请求路径未找到');
      break;
    case 500:
      errorToast('网络异常...');
      break;
    case 400:
      errorToast('请登录...');
      uni.reLaunch({
        url: '/pages/login/login',
      });
      break;
    default:
      break;
  }
}

function get(url, params) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + url,
      method: 'GET',
      header: {
        // Accept: 'application/json',
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
        token: uni.getStorageSync('token') ? uni.getStorageSync('token') : '',
        type: 1,
      },
      data: params ? params : '',
      success(res) {
        statusCodeProcessing(res.statusCode);
        if (res.data.code === 500) {
          errorToast(res.data.msg || '网络异常，请稍后重试');
        }
        resolve(res.data);
      },
      fail(err) {
        errorToast('网络异常...');
        reject(err);
      },
    });
  });
}

function post(url, params, options = {}) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + url,
      method: 'POST',
      ...options,
      timeout: 10000,
      header: {
        // Accept: 'application/json',
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
        token: uni.getStorageSync('token') ? uni.getStorageSync('token') : '',
        type: 1,
      },
      data: params ? params : '',
      success(res) {
        statusCodeProcessing(res.statusCode);
        if (res.data.code === 500) {
          errorToast(res.data.msg || '网络异常，请稍后重试');
        }
        resolve(res.data);
      },
      fail(err) {
        errorToast('网络异常...');
        reject(err);
      },
    });
  });
}

export default function useHttp() {
  baseUrl = 'https://apishop.jxsr.com';
  return {
    get,
    post,
  };
}
